package com.coco.homework.rules;

import java.text.MessageFormat;

import com.coco.homework.Context;
import com.coco.homework.RomanNumber;
import com.coco.homework.ex.RuleInvalidException;

public class RomanNumberCRule implements IRomanNumberRule {

	@Override
	public void exec(Context context) {
		char ch = context.getCurrentChar();
		RomanNumber romanNumber = RomanNumber.of(ch);
		if (!romanNumber.equals(getCanHandlerNumber())) {
			throw new RuleInvalidException("RomanNumber ERROR ");
		}

		boolean repeatable = repeatRuleCheck(context.getLeftString(), ch, MAX_REPEAT_COUNT);
		if (!repeatable) {
			throw new RuleInvalidException(MessageFormat.format(CHAR_REPEAT_MORE, ch, MAX_REPEAT_COUNT));
		}
		char nextChar = context.getNextChar();
		RomanNumber nextRomanNumber = RomanNumber.of(nextChar);
		int val;
		if (nextRomanNumber.equals(RomanNumber.EOF)) {
			val = romanNumber.getVal();
		} else {
			if (!RomanNumber.canSubtractC(nextRomanNumber)) {
				context.skipCharCount(-1);
				val = romanNumber.getVal();
			} else {
				val = nextRomanNumber.getVal() - romanNumber.getVal();
			}
		}
		context.addTokenVal(val);
	}

	@Override
	public RomanNumber getCanHandlerNumber() {
		return RomanNumber.C;
	}
}
